bf.service = new (function(){
	this.findById = function(id){
		var queryObj =  getFields.call(this, { // 分析需要哪些字段？包括外联的字段，但因为是单个，所以要正文字段（isLessBig）
			isLessBig : false
		});
		queryObj.tableName = this.getTableName();
		queryObj.id = id;
		
		return 'SELECT {fields} FROM {tableName} {join} WHERE {tableName}.id = {id}'.format(queryObj);
	}
	
	this.find = function(where){
		var queryObj =  getFields.call(this, { // 分析需要哪些字段？包括外联的字段，但因为是单个，所以要正文字段（isLessBig）
			isLessBig : false
		});
		queryObj.tableName = this.getTableName();
		
		return ('SELECT {fields} FROM {tableName} {join} WHERE ' + where).format(queryObj);
	}

	function getFields(cfg){
		if(!this.pojo){
			return {
				fields : '*',
				join : ''
			};
		}
		
		var arr = [], tableName = this.getTableName();
		var joinStatement = '', joinWhereStatement = null; // 外联的 where 语句
		
		for(var i in this.pojo){
			var prop = this.pojo[i];
			
			// 特殊信息 ，非字段
			if(i == 'joinMeta'){
				joinStatement += ' ' + prop + ' ';
				continue;
			}
			
			// 每个 field type 都有 jsType
			if(!prop || typeof(prop.jsType) == 'undefined' 
				|| (cfg && cfg.isLessBig && prop.isBigContent === true) ){ 
				continue;
			}
			
			// 获取字段名
			if(!prop.superJoinField && !prop.isRightJoinField && !prop.subQuery)arr.push(tableName + '.' + i); 
			
			// 若空，整条不为空
			if(prop.isRightJoinField){
//				var rightJoin = prop.isRightJoinField, subJoin = rightJoin.split('='),
//					joinTableName = subJoin[0].indexOf('this.') != -1 ? subJoin[1] : subJoin[0],
//					joinTableName = joinTableName.split('.').shift();
//				
//				joinStatement += ' LEFT JOIN ';
//				joinStatement += joinTableName;
//				joinStatement += ' ON ';
//				joinStatement += rightJoin.replace('this.', tableName + '.');
//				
//				arr.push(joinTableName + '.' + prop.as + ' AS ' + i);
			}else if(prop.superJoinField){
				arr.push(prop.superJoinField + '.' + i);
			}else if(prop.isJoinField){
				// 若空，则整条 空
				joinStatement += ' INNER JOIN {0} ON {0}.key = {1}.{0}'.format(i, tableName);
				joinWhereStatement = [i + ".belongsTo ='" + tableName +"'"];
				
				arr.push(i + '.name AS ' + tableName + i);
			}else if(prop.subQuery){ // 子查询
				arr.push('(' + String(prop.subQuery).format(tableName) + ')' + ' AS ' + (prop.as || i));
			}
		}

		return {
			fields : arr.join(', '),
			join : joinStatement,
			joinWhereStatement : joinWhereStatement,
			no_count_where :joinWhereStatement ?  joinWhereStatement[0] : null // 统计总数时不需要 where 查询
		};
		
	}
	
	function addWhere(query, str){
		if(query.where && query.where.push){
			query.where.push(str);
		}else{
			query.where = [str];
		}
	}
	
	function getWhere(query){
		//addWhere(query, queryArgs);

		var whereStr = '';
		if (query.where && query.where.join){
			whereStr = 'WHERE ' + query.where.join(' AND ');
		}
		
		query.where = whereStr;
		
		return whereStr;
	}
	
	// 获取专属于 count 的查询条件，去掉外键的 where
	function getCountQuery(query){
		var _query = {};
		for(var i in query){
			_query[i] =query[i];
		}
		//delete _query.no_count_where;
		var reg = new RegExp(query.no_count_where + "(\\s+AND)?")
		_query.where = _query.where.replace(reg, '');
		
		if(/\s+WHERE\s?$/.test(_query.where))
			_query.where = _query.where.replace(/\s+WHERE\s?$/, '');
		
//		println(_query.where)
		return _query;
	}
	
		
	/**
	 * @param {Object} query 查询对象
	 */
	this.findList = function (query, queryArgs){
		if(!query)throw 'No args of query Object!';
		
		query.tableName = this.getTableName();	// 获取表名

		// 允许选择全部字段
		if(query.fields != '*'){
			var fieldInfo =  getFields.call(this, { // 分析需要哪些字段？包括外联的字段，但因为是列表，不想要正文字段（isLessBig）
				isLessBig : true
			});
			for(var i in fieldInfo){				// 复制到 query Object 身上
				query[i] = fieldInfo[i];
			}
		}
		var tmpArr = [];
		if(query.joinWhereStatement)
			tmpArr = query.joinWhereStatement;
		
		if(queryArgs){
			tmpArr = tmpArr.concat(queryArgs);
		}
			
		var where;
		if(!tmpArr.length){
			where = '';
		}else if(tmpArr.length == 1){
			where = ' WHERE ' + tmpArr.join('');
		}else if(tmpArr.length > 1){
			where = ' WHERE ' + tmpArr.join(' AND ');
		}
		// 用 regexp 删除，其实不应该
		
		if(/\s+AND\s?$/.test(where))
			where = where.replace('AND', '');
		query.where = where;


		
		var countSql = 'SELECT COUNT(id) AS count FROM {tableName} {where}'.format(getCountQuery(query));
		var resultSql = 'SELECT {fields} FROM {tableName} {join} {where} ORDER BY {tableName}.id DESC LIMIT {start}, {limit} '.format(query);
		
		return countSql + '###' + resultSql;
	}
});

/**
 * 如果没传入分页参数，则表示读取前99条数据！ limit = 99
 */
bf_service_findList = function(serviceInstance, request, queryStr){
	var start = Number(String(request.getParameter('start'))) || 0, 
		limit = Number(String(request.getParameter('limit'))) || 99;
	
	queryStr = queryStr ? [String(queryStr)] : [];

	// 分类
	if(request.getParameter('catalog') != null){
		queryStr.push("catalog = '" + request.getParameter('catalog') + "'");		
	}
	
//		println('未登录，是游客');
	if(!serviceInstance.isSubObject /* Sub Object 应该无  hidden */ && request.getSession() && request.getSession().getAttribute("uid") == null){
		queryStr.push("(" + serviceInstance.getTableName() + ".isHidden !=  0 OR "+ serviceInstance.getTableName() + ".isHidden is NULL" + ")");
	}

	return bf.service.findList.call(serviceInstance, {
		start : start,
		limit : limit
	}, queryStr);
}

bf_service_findById = function(serviceInstance, id){
	return bf.service.findById.call(serviceInstance, id);
}
bf_service_find = function(serviceInstance, where){
	return bf.service.find.call(serviceInstance, where);
}